package com.Home.digital_life;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UpdateList {
	private URL url = null;

	/**
	 * žùŸÝURLÏÂÔØÎÄŒþ£¬Ç°ÌáÊÇÕâžöÎÄŒþµ±ÖÐµÄÄÚÈÝÊÇÎÄ±Ÿ£¬º¯ÊýµÄ·µ»ØÖµŸÍÊÇÎÄŒþµ±
	 * ÖÐµÄÄÚÈÝ 1.ŽŽœšÒ»žöURL¶ÔÏó 2.Íš¹ýURL¶ÔÏó£¬ŽŽœšÒ»žöHttpURLConnection¶ÔÏó
	 * 3.µÃµœInputStram 4.ŽÓInputStreamµ±ÖÐ¶ÁÈ¡ÊýŸÝ
	 * 
	 * @param urlStr
	 * @return
	 */
	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			// ŽŽœšÒ»žöURL¶ÔÏó
			url = new URL(urlStr);
			// ŽŽœšÒ»žöHttpÁ¬œÓ
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection();
			// Ê¹ÓÃIOÁ÷¶ÁÈ¡ÊýŸÝ
			buffer = new BufferedReader(new InputStreamReader(
					urlConn.getInputStream()));
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * žÃº¯Êý·µ»ØÕûÐÎ -1£ºŽú±íÏÂÔØÎÄŒþ³öŽí 0£ºŽú±íÏÂÔØÎÄŒþ³É¹Š
	 * 1£ºŽú±íÎÄŒþÒÑŸ­ŽæÔÚ
	 */
	public int downFile(String urlStr, String path, String fileName) {
		InputStream inputStream = null;
		try {
			FileUtils fileUtils = new FileUtils();

			if (fileUtils.isFileExist(path + fileName)) {
				new File(path + fileName).delete();
			}
			inputStream = getInputStreamFromUrl(urlStr);
			File resultFile = fileUtils.write2SDFromInput(path, fileName,
					inputStream);
			if (resultFile == null) {
				return -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	/**
	 * žùŸÝURLµÃµœÊäÈëÁ÷
	 * 
	 * @param urlStr
	 * @return
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public InputStream getInputStreamFromUrl(String urlStr)
			throws MalformedURLException, IOException {
		url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		return inputStream;
	}
}